// src/components/Permission/PermissionManager.jsx
import React, { useState } from 'react';
import {
  Table, Card, Button, Space,
  Switch, Tag, Modal, Form,
  Input, Select, message,
  Tree, Divider, Row, Col,
  Tabs
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LockOutlined,
  ApiOutlined,
  MenuOutlined,
  FileOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { TabPane } = Tabs;

const PermissionManager = () => {
  const [activeTab, setActiveTab] = useState('permissions');
  const [permissions, setPermissions] = useState([
    {
      id: 1,
      name: '用户管理',
      code: 'user:*',
      type: 'menu',
      description: '用户管理模块的所有权限',
      enabled: true
    },
    {
      id: 2,
      name: '查看用户列表',
      code: 'user:list',
      type: 'operation',
      description: '查看用户列表权限',
      enabled: true
    },
    {
      id: 3,
      name: '创建用户',
      code: 'user:create',
      type: 'operation',
      description: '创建新用户权限',
      enabled: true
    },
    {
      id: 4,
      name: '编辑用户',
      code: 'user:edit',
      type: 'operation',
      description: '编辑用户信息权限',
      enabled: true
    },
    {
      id: 5,
      name: '删除用户',
      code: 'user:delete',
      type: 'operation',
      description: '删除用户权限',
      enabled: true
    },
    {
      id: 6,
      name: '角色管理',
      code: 'role:*',
      type: 'menu',
      description: '角色管理模块的所有权限',
      enabled: true
    },
    {
      id: 7,
      name: '查看角色列表',
      code: 'role:list',
      type: 'operation',
      description: '查看角色列表权限',
      enabled: true
    },
    {
      id: 8,
      name: '创建角色',
      code: 'role:create',
      type: 'operation',
      description: '创建新角色权限',
      enabled: true
    }
  ]);

  const [roles, setRoles] = useState([
    {
      id: 1,
      name: '系统管理员',
      code: 'admin',
      description: '拥有系统所有权限',
      permissionIds: [1, 2, 3, 4, 5, 6, 7, 8],
      enabled: true
    },
    {
      id: 2,
      name: '人事专员',
      code: 'hr',
      description: '负责用户管理',
      permissionIds: [1, 2, 3, 4],
      enabled: true
    },
    {
      id: 3,
      name: '普通用户',
      code: 'user',
      description: '只能查看信息',
      permissionIds: [2],
      enabled: true
    }
  ]);

  const [resources] = useState([
    {
      id: 1,
      name: '用户管理',
      code: 'user',
      type: 'module',
      permissions: [
        { id: 1, name: '访问模块', code: 'user:*', type: 'menu' },
        { id: 2, name: '查看列表', code: 'user:list', type: 'operation' },
        { id: 3, name: '创建用户', code: 'user:create', type: 'operation' },
        { id: 4, name: '编辑用户', code: 'user:edit', type: 'operation' },
        { id: 5, name: '删除用户', code: 'user:delete', type: 'operation' }
      ]
    },
    {
      id: 2,
      name: '角色管理',
      code: 'role',
      type: 'module',
      permissions: [
        { id: 6, name: '访问模块', code: 'role:*', type: 'menu' },
        { id: 7, name: '查看列表', code: 'role:list', type: 'operation' },
        { id: 8, name: '创建角色', code: 'role:create', type: 'operation' }
      ]
    },
    {
      id: 3,
      name: '数据源管理',
      code: 'datasource',
      type: 'module',
      permissions: [
        { id: 9, name: '访问模块', code: 'datasource:*', type: 'menu' },
        { id: 10, name: '查看列表', code: 'datasource:list', type: 'operation' },
        { id: 11, name: '创建数据源', code: 'datasource:create', type: 'operation' }
      ]
    }
  ]);

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState('permission'); // permission, role
  const [editingItem, setEditingItem] = useState(null);
  const [form] = Form.useForm();

  const permissionTypes = [
    { label: '菜单权限', value: 'menu', icon: <MenuOutlined /> },
    { label: '操作权限', value: 'operation', icon: <ApiOutlined /> },
    { label: '数据权限', value: 'data', icon: <FileOutlined /> }
  ];

  const handleAddPermission = () => {
    setModalType('permission');
    setEditingItem(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEditPermission = (record) => {
    setModalType('permission');
    setEditingItem(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const handleDeletePermission = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个权限吗？这可能会影响相关角色的权限配置。',
      onOk: () => {
        setPermissions(permissions.filter(p => p.id !== id));
        // 同时更新角色中的权限引用
        setRoles(roles.map(role => ({
          ...role,
          permissionIds: role.permissionIds.filter(pid => pid !== id)
        })));
        message.success('删除成功');
      }
    });
  };

  const handleAddRole = () => {
    setModalType('role');
    setEditingItem(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEditRole = (record) => {
    setModalType('role');
    setEditingItem(record);
    form.setFieldsValue({
      ...record,
      permissionIds: record.permissionIds || []
    });
    setIsModalVisible(true);
  };

  const handleDeleteRole = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个角色吗？',
      onOk: () => {
        setRoles(roles.filter(r => r.id !== id));
        message.success('删除成功');
      }
    });
  };

  const handleSave = () => {
    form.validateFields().then(values => {
      if (modalType === 'permission') {
        if (editingItem) {
          // 更新权限
          setPermissions(permissions.map(p =>
            p.id === editingItem.id ? { ...values, id: editingItem.id } : p
          ));
          message.success('权限更新成功');
        } else {
          // 添加权限
          const newPermission = {
            ...values,
            id: permissions.length > 0 ? Math.max(...permissions.map(p => p.id)) + 1 : 1
          };
          setPermissions([...permissions, newPermission]);
          message.success('权限添加成功');
        }
      } else if (modalType === 'role') {
        if (editingItem) {
          // 更新角色
          setRoles(roles.map(r =>
            r.id === editingItem.id ? { ...values, id: editingItem.id } : r
          ));
          message.success('角色更新成功');
        } else {
          // 添加角色
          const newRole = {
            ...values,
            id: roles.length > 0 ? Math.max(...roles.map(r => r.id)) + 1 : 1
          };
          setRoles([...roles, newRole]);
          message.success('角色添加成功');
        }
      }

      setIsModalVisible(false);
    });
  };

  const handlePermissionToggle = (id, checked) => {
    setPermissions(permissions.map(p =>
      p.id === id ? { ...p, enabled: checked } : p
    ));
  };

  const handleRoleToggle = (id, checked) => {
    setRoles(roles.map(r =>
      r.id === id ? { ...r, enabled: checked } : r
    ));
  };

  const getPermissionTypeIcon = (type) => {
    const typeInfo = permissionTypes.find(t => t.value === type);
    return typeInfo ? typeInfo.icon : <LockOutlined />;
  };

  const getPermissionTypeName = (type) => {
    const typeInfo = permissionTypes.find(t => t.value === type);
    return typeInfo ? typeInfo.label : type;
  };

  const permissionColumns = [
    {
      title: '权限名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          {getPermissionTypeIcon(record.type)}
          {text}
        </Space>
      )
    },
    {
      title: '权限代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => (
        <Tag color={type === 'menu' ? 'blue' : type === 'operation' ? 'green' : 'orange'}>
          {getPermissionTypeName(type)}
        </Tag>
      )
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      render: (enabled, record) => (
        <Switch
          checked={enabled}
          onChange={(checked) => handlePermissionToggle(record.id, checked)}
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditPermission(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            icon={<DeleteOutlined />}
            onClick={() => handleDeletePermission(record.id)}
            danger
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const roleColumns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '角色代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '权限数量',
      key: 'permissions',
      render: (_, record) => record.permissionIds ? record.permissionIds.length : 0,
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      render: (enabled, record) => (
        <Switch
          checked={enabled}
          onChange={(checked) => handleRoleToggle(record.id, checked)}
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditRole(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteRole(record.id)}
            danger
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const renderPermissionTree = () => {
    const treeData = resources.map(resource => ({
      title: resource.name,
      key: resource.code,
      children: resource.permissions.map(permission => ({
        title: permission.name,
        key: `${resource.code}:${permission.code}`,
        permission: permission
      }))
    }));

    return (
      <Tree
        className="permission-tree"
        treeData={treeData}
        defaultExpandAll
        checkable
        selectable={false}
        style={{ padding: '16px' }}
      />
    );
  };

  const renderPermissionForm = () => (
    <>
      <Form.Item
        name="name"
        label="权限名称"
        rules={[{ required: true, message: '请输入权限名称' }]}
      >
        <Input placeholder="例如：查看用户列表" />
      </Form.Item>

      <Form.Item
        name="code"
        label="权限代码"
        rules={[{ required: true, message: '请输入权限代码' }]}
      >
        <Input placeholder="例如：user:list" />
      </Form.Item>

      <Form.Item
        name="type"
        label="权限类型"
        rules={[{ required: true, message: '请选择权限类型' }]}
      >
        <Select placeholder="请选择权限类型">
          {permissionTypes.map(type => (
            <Option key={type.value} value={type.value}>
              <Space>
                {type.icon}
                {type.label}
              </Space>
            </Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item
        name="description"
        label="描述"
      >
        <Input.TextArea placeholder="权限的详细描述" />
      </Form.Item>
    </>
  );

  const renderRoleForm = () => (
    <>
      <Form.Item
        name="name"
        label="角色名称"
        rules={[{ required: true, message: '请输入角色名称' }]}
      >
        <Input placeholder="例如：系统管理员" />
      </Form.Item>

      <Form.Item
        name="code"
        label="角色代码"
        rules={[{ required: true, message: '请输入角色代码' }]}
      >
        <Input placeholder="例如：admin" />
      </Form.Item>

      <Form.Item
        name="description"
        label="描述"
      >
        <Input.TextArea placeholder="角色的详细描述" />
      </Form.Item>

      <Form.Item
        name="permissionIds"
        label="权限配置"
      >
        <div>
          <Divider>权限树</Divider>
          {renderPermissionTree()}
        </div>
      </Form.Item>
    </>
  );

  return (
    <div className="permission-manager">
      <Card
        title={
          <Space>
            <LockOutlined />
            权限管理中心
          </Space>
        }
      >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={[
            {
              key: 'permissions',
              label: '权限管理',
              children: (
                <>
                  <div style={{ marginBottom: 16 }}>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleAddPermission}
                    >
                      添加权限
                    </Button>
                  </div>
                  <Table
                    dataSource={permissions}
                    columns={permissionColumns}
                    rowKey="id"
                    pagination={{ pageSize: 10 }}
                  />
                </>
              ),
            },
            {
              key: 'roles',
              label: '角色管理',
              children: (
                <>
                  <div style={{ marginBottom: 16 }}>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleAddRole}
                    >
                      添加角色
                    </Button>
                  </div>
                  <Table
                    dataSource={roles}
                    columns={roleColumns}
                    rowKey="id"
                    pagination={{ pageSize: 10 }}
                  />
                </>
              ),
            },
            {
              key: 'resource-map',
              label: '资源权限映射',
              children: (
                <Card size="small" title="系统资源权限结构">
                  {renderPermissionTree()}
                </Card>
              ),
            }
          ]}
        />
      </Card>

      <Modal
        title={editingItem ?
          (modalType === 'permission' ? "编辑权限" : "编辑角色") :
          (modalType === 'permission' ? "添加权限" : "添加角色")
        }
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        onOk={handleSave}
        width={800}
      >
        <Form form={form} layout="vertical">
          {modalType === 'permission' ?
            renderPermissionForm() :
            renderRoleForm()
          }
        </Form>
      </Modal>
    </div>
  );
};

export default PermissionManager;
